﻿import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'package:permission_handler/permission_handler.dart';
import '../../../routes/app_routes.dart';

/// GPS权限提示页面
class GpsPermissionView extends StatelessWidget {
  const GpsPermissionView({super.key});

  @override
  Widget build(BuildContext context) {
    // 获取传递的参数
    final arguments = Get.arguments as Map<String, dynamic>?;
    final exerciseName = arguments?['exerciseName'] ?? 'GPS运动';

    return Scaffold(
      backgroundColor: Colors.black,
      body: SafeArea(
        child: Padding(
          padding: EdgeInsets.all(24.w),
          child: Column(
            children: [
              Expanded(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    // 插画区域
                    Container(
                      width: double.infinity,
                      height: 300.h,
                      child: Stack(
                        alignment: Alignment.center,
                        children: [
                          // 背景云朵
                          Positioned(
                            top: 20.h,
                            left: 50.w,
                            child: _buildCloud(60.w, 40.h),
                          ),
                          Positioned(
                            top: 40.h,
                            right: 80.w,
                            child: _buildCloud(40.w, 25.h),
                          ),

                          // 主要人物跑步插画
                          Positioned(
                            bottom: 80.h,
                            child: Container(
                              width: 200.w,
                              height: 150.h,
                              child: Stack(
                                children: [
                                  // 跑步平台
                                  Positioned(
                                    bottom: 0,
                                    child: Container(
                                      width: 200.w,
                                      height: 30.h,
                                      decoration: BoxDecoration(
                                        color: Colors.grey[300],
                                        borderRadius:
                                            BorderRadius.circular(15.r),
                                      ),
                                    ),
                                  ),

                                  // 跑步的人
                                  Positioned(
                                    bottom: 25.h,
                                    left: 80.w,
                                    child: Container(
                                      width: 60.w,
                                      height: 100.h,
                                      child: Column(
                                        children: [
                                          // 头部
                                          Container(
                                            width: 25.w,
                                            height: 25.w,
                                            decoration: BoxDecoration(
                                              color: Color(0xFFFFDBAD), // 肤色
                                              shape: BoxShape.circle,
                                            ),
                                          ),
                                          // 身体
                                          Container(
                                            width: 40.w,
                                            height: 50.h,
                                            decoration: BoxDecoration(
                                              color: Colors.orange,
                                              borderRadius:
                                                  BorderRadius.circular(5.r),
                                            ),
                                          ),
                                          // 腿部
                                          Container(
                                            width: 35.w,
                                            height: 25.h,
                                            decoration: BoxDecoration(
                                              color: Colors.blue[800],
                                              borderRadius:
                                                  BorderRadius.circular(3.r),
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),
                                  ),

                                  // 手机图标
                                  Positioned(
                                    bottom: 70.h,
                                    right: 50.w,
                                    child: Container(
                                      width: 20.w,
                                      height: 30.h,
                                      decoration: BoxDecoration(
                                        color: Colors.grey[800],
                                        borderRadius:
                                            BorderRadius.circular(3.r),
                                        border: Border.all(
                                            color: Colors.white, width: 1),
                                      ),
                                      child: Center(
                                        child: Container(
                                          width: 2.w,
                                          height: 2.w,
                                          decoration: const BoxDecoration(
                                            color: Colors.white,
                                            shape: BoxShape.circle,
                                          ),
                                        ),
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),

                          // 背景植物
                          Positioned(
                            bottom: 100.h,
                            left: 30.w,
                            child: _buildTree(),
                          ),
                          Positioned(
                            bottom: 100.h,
                            right: 30.w,
                            child: _buildTree(),
                          ),
                        ],
                      ),
                    ),

                    SizedBox(height: 40.h),

                    // 标题
                    Text(
                      '请正确佩戴手机',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 24.sp,
                        fontWeight: FontWeight.bold,
                      ),
                    ),

                    SizedBox(height: 24.h),

                    // 说明文字
                    Padding(
                      padding: EdgeInsets.symmetric(horizontal: 20.w),
                      child: Column(
                        children: [
                          Text(
                            '请将手机佩戴在身上，否则将无法记录GPS数据。',
                            style: TextStyle(
                              color: Colors.grey[400],
                              fontSize: 16.sp,
                              height: 1.5,
                            ),
                            textAlign: TextAlign.center,
                          ),
                          SizedBox(height: 16.h),
                          Text(
                            '如果路线轨迹与实际轨迹相差过大，请在系统设置中检查手机定位，或切换后台运行时的省电策略。',
                            style: TextStyle(
                              color: Colors.grey[500],
                              fontSize: 14.sp,
                              height: 1.5,
                            ),
                            textAlign: TextAlign.center,
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),

              // 底部按钮
              Container(
                width: double.infinity,
                margin: EdgeInsets.only(bottom: 20.h),
                child: ElevatedButton(
                  onPressed: () => _handlePermissionRequest(exerciseName),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.orange,
                    foregroundColor: Colors.black,
                    padding: EdgeInsets.symmetric(vertical: 16.h),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(25.r),
                    ),
                    elevation: 0,
                  ),
                  child: Text(
                    '好的',
                    style: TextStyle(
                      fontSize: 18.sp,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建云朵
  Widget _buildCloud(double width, double height) {
    return Container(
      width: width,
      height: height,
      decoration: BoxDecoration(
        color: Colors.grey[600],
        borderRadius: BorderRadius.circular(height / 2),
      ),
    );
  }

  /// 构建树木
  Widget _buildTree() {
    return Container(
      width: 25.w,
      height: 40.h,
      child: Column(
        children: [
          // 树叶
          Container(
            width: 25.w,
            height: 25.h,
            decoration: BoxDecoration(
              color: Colors.purple[300],
              borderRadius: BorderRadius.circular(12.r),
            ),
          ),
          // 树干
          Container(
            width: 5.w,
            height: 15.h,
            color: Colors.brown[400],
          ),
        ],
      ),
    );
  }

  /// 处理权限请求
  void _handlePermissionRequest(String exerciseName) async {
    try {
      // 请求位置权限
      final permissionStatus = await _requestLocationPermission();

      if (permissionStatus == PermissionStatus.granted) {
        // 权限已授予，跳转到运动记录页面
        final arguments = Get.arguments as Map<String, dynamic>?;
        final exerciseType = arguments?['exerciseType'];

        Get.back(); // 关闭权限页面

        // 跳转到GPS运动记录页面
        // Get.toNamed(AppRoutes.exerciseRecording, arguments: {
        //   'exerciseType': exerciseType,
        //   'exerciseName': exerciseName,
        // });
      } else if (permissionStatus == PermissionStatus.permanentlyDenied) {
        // 权限被永久拒绝，显示跳转设置的对话框
        _showPermissionSettingsDialog(exerciseName);
      } else {
        // 权限被拒绝
        Toast.show('需要位置权限才能记录GPS轨迹');
      }
    } catch (e) {
      // 权限请求过程中出错
      Toast.show('请求位置权限时出现错误：${e.toString()}');
    }
  }

  /// 请求位置权限
  Future<PermissionStatus> _requestLocationPermission() async {
    // 首先检查当前权限状态
    PermissionStatus permission = await Permission.location.status;

    if (permission != PermissionStatus.granted) {
      // 如果没有权限，请求权限
      permission = await Permission.location.request();
    }

    return permission;
  }

  /// 显示权限设置对话框
  void _showPermissionSettingsDialog(String exerciseName) {
    Get.dialog(
      AlertDialog(
        backgroundColor: Colors.grey[900],
        title: Row(
          children: [
            Container(
              width: 40.w,
              height: 40.w,
              decoration: BoxDecoration(
                color: Colors.orange,
                borderRadius: BorderRadius.circular(8.r),
              ),
              child: Center(
                child: Text(
                  'AZ',
                  style: TextStyle(
                    color: Colors.black,
                    fontSize: 14.sp,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
            ),
            SizedBox(width: 12.w),
            Text(
              'AZring',
              style: TextStyle(
                color: Colors.white,
                fontSize: 18.sp,
                fontWeight: FontWeight.w600,
              ),
            ),
          ],
        ),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            _buildPermissionItem('始终允许', true),
            SizedBox(height: 8.h),
            _buildPermissionItem('使用应用时允许', false),
            SizedBox(height: 8.h),
            _buildPermissionItem('每次使用时询问', false),
            SizedBox(height: 8.h),
            _buildPermissionItem('禁止', false),
            SizedBox(height: 16.h),
            Text(
              '定位精度',
              style: TextStyle(
                color: Colors.grey[400],
                fontSize: 14.sp,
              ),
            ),
            SizedBox(height: 12.h),
            Row(
              children: [
                Expanded(
                  child: _buildAccuracyOption('精确位置', true),
                ),
                SizedBox(width: 16.w),
                Expanded(
                  child: _buildAccuracyOption('大致位置', false),
                ),
              ],
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () {
              Get.back();
            },
            child: Text(
              '取消',
              style: TextStyle(color: Colors.grey[400]),
            ),
          ),
          ElevatedButton(
            onPressed: () async {
              Get.back();
              // 打开应用设置页面
              await openAppSettings();
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.blue,
              foregroundColor: Colors.white,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(8.r),
              ),
            ),
            child: const Text('打开'),
          ),
        ],
      ),
    );
  }

  /// 构建权限选项
  Widget _buildPermissionItem(String title, bool isSelected) {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.symmetric(vertical: 12.h, horizontal: 16.w),
      decoration: BoxDecoration(
        color: Colors.grey[800],
        borderRadius: BorderRadius.circular(8.r),
      ),
      child: Row(
        children: [
          Icon(
            isSelected
                ? Icons.radio_button_checked
                : Icons.radio_button_unchecked,
            color: isSelected ? Colors.blue : Colors.grey[600],
            size: 20.sp,
          ),
          SizedBox(width: 12.w),
          Text(
            title,
            style: TextStyle(
              color: Colors.white,
              fontSize: 14.sp,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建精度选项
  Widget _buildAccuracyOption(String title, bool isSelected) {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 16.h),
      decoration: BoxDecoration(
        color: Colors.grey[800],
        borderRadius: BorderRadius.circular(8.r),
        border: Border.all(
          color: isSelected ? Colors.blue : Colors.transparent,
          width: 2,
        ),
      ),
      child: Column(
        children: [
          Icon(
            Icons.location_on,
            color: isSelected ? Colors.blue : Colors.grey[600],
            size: 24.sp,
          ),
          SizedBox(height: 8.h),
          Text(
            title,
            style: TextStyle(
              color: isSelected ? Colors.blue : Colors.grey[400],
              fontSize: 12.sp,
            ),
          ),
        ],
      ),
    );
  }
}
